#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#commented out because it causes the COOPIP models to no longer be in global namespace
"""import os, csv, shutil, datetime, time, reportlab
from django.contrib.gis.db import models
from django.http import HttpResponse
import django
from django.contrib import admin"""

import sys
IncludePath="/opt/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


import os, csv, shutil, datetime, time, reportlab
from django.contrib.gis.db import models
from django.http import HttpResponse
from django.contrib import admin
import COOPIP_Authentication
import djangoproject


class COOPWebCommunicationCommandName(models.Model):
    using='coopweb'
    Name=models.TextField(db_column='name', unique=True)
    class Meta:
        db_table=u'communicationcommandname'
        app_label='djangoproject'

class COOPWebCommunicationCommand(models.Model):
    """COOPWebCommunicationCommand refers to the Communication table on the COOPWEB Server
       COOPIP will poll this table to pickup new commands that need processing.  It also will put any results into this table 
       so that they may be displayed on the web interface.  
       Methods here involve importing and exporting data to the COOPWeb Server"""
    using='coopweb'
    CommunicationCommandName=models.ForeignKey('COOPWebCommunicationCommandName', db_column='communicationcommandname_id')
    CommandString=models.TextField(db_column='commandstring', null=True, blank=True)
    CreateDateTime=models.DateTimeField(db_column='createdatetime')
    CreateUsername=models.TextField(db_column='createusername')
    PickedUpByCOOPIPDateTime=models.DateTimeField(db_column='pickedupbycoopipdatetime', null=True, blank=True)
    ResponseByCOOPIPDateTime=models.DateTimeField(db_column='responsebycoopipdatetime', null=True, blank=True)
    ResponseString=models.TextField(db_column='responsestring', null=True, blank=True)
    class Meta:
        db_table=u'communicationcommand'
        app_label='djangoproject'

    @staticmethod
    def PickUpNewCOOPWebCommands():
        COOPWebCommunicationCommands=COOPWebCommunicationCommand.objects.filter(PickedUpByCOOPIPDateTime__isnull=True)
        for i in COOPWebCommunicationCommands:
            Now=datetime.datetime.now()
            New=djangoproject.models.coopwebcommunication.CommunicationCommand()

            communicationCommandName=djangoproject.models.coopwebcommunication.CommunicationCommandName.GetOrCreate(i.CommunicationCommandName.Name)

            New.CommunicationCommandName=communicationCommandName

            New.CommandString=i.CommandString
            New.CreateDateTime=Now
            communicationCommandStatus=djangoproject.models.coopwebcommunication.CommunicationCommandStatus.objects.filter(Name='New')[0]
            New.CommunicationCommandStatus=communicationCommandStatus
            New.CommunicationCommandStatusLastUpdateDateTime=Now
            New.COOPWebCommunicationCommandIdentifier=i.id
            New.COOPWebUsername=i.CreateUsername
            New.save()
            i.PickedUpByCOOPIPDateTime=Now
            try:  #If the object on the remote server cannot be updated that it was picked up for any reason, then delete the new command on the COOPIP server
                i.save()
            except:
                New.delete()

    @staticmethod
    def SendCompletedCOOPWebCommands():
        CommunicationCommands=djangoproject.models.coopwebcommunication.CommunicationCommand.objects.filter(ResponsePendingIndicator=True)
        for i in CommunicationCommands:
            try:
                cOOPWebCommunicationCommand = COOPWebCommunicationCommand.objects.filter(id=i.COOPWebCommunicationCommandIdentifier)[0]
            except IndexError:
                print "No record found in COOPWeb that matches:  " + str(i.COOPWebCommunicationCommandIdentifier)
                continue
            Now=datetime.datetime.now()
            cOOPWebCommunicationCommand.ResponseString = i.ResponseString
            cOOPWebCommunicationCommand.ResponseByCOOPIPDateTime=Now
            cOOPWebCommunicationCommand.save()
            i.ResponseDateTime = Now
            i.ResponsePendingIndicator=False
            i.save()

class COOPWebCOOPIPAuthenticate(models.Model):
    """Table used during authentication, COOPIP will look for pending authentication requests and attempt to authenticate against the credentials in this table,
       Data is deleted from this table on an ongoing basis"""
    using='coopweb'
    CreateDateTime=models.DateTimeField(db_column='createdatetime')
    Username=models.TextField(db_column='username', null=True, blank=True)
    Password=models.TextField(db_column='password', null=True, blank=True)
    COOPIPAuthenticationSuccessIndicator=models.NullBooleanField(db_column='coopipauthenticationsuccessindicator', null=True, blank=True)  #Null = Unknown, True = Authenticate, False = No Authenticate
    class Meta:
        db_table=u'coopwebcoopipauthenticate'
        app_label='djangoproject'
    @staticmethod
    def ProcessPending():
        COOPWebCOOPIPAuthenticates=COOPWebCOOPIPAuthenticate.objects.filter(COOPIPAuthenticationSuccessIndicator__isnull=True)
        for i in COOPWebCOOPIPAuthenticates:
            try:
                COOPIP_Authentication.AttemptLDAPAuthentication(i.Username, i.Password)
                #print "Authentication Success for:  " + str(i.Username)
                i.COOPIPAuthenticationSuccessIndicator=True
            except:
                #print "Authentication Failed for:  " + str(i.Username)
                i.COOPIPAuthenticationSuccessIndicator=False
            i.Password=''
            i.save()
            i.ResponsePendingIndicator = False
            i.save()

class AVLSystemLog(models.Model):
    using='coopweb'
    CreateDateTime=models.DateTimeField(db_column='createdatetime', null=True, blank=True)
    AVLSystemNetworkTrafficid=models.IntegerField(db_column='avlsystemnetworktrafficid', null=True, blank=True)
    RawTAIP=models.TextField(db_column='rawtaip', null=True, blank=True)
    Latitude=models.FloatField(db_column='latitude', null=True, blank=True)
    Longitude=models.FloatField(db_column='longitude', null=True, blank=True)
    Speed=models.IntegerField(db_column='speed', null=True, blank=True)
    Bearing=models.IntegerField(db_column='bearing', null=True, blank=True)
    VehicleNumber=models.IntegerField(db_column='vehiclenumber', null=True, blank=True)
    Point=models.PointField(db_column='the_geom', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'avlsystemlog'
        app_label='djangoproject'


class Alarm(models.Model):
    """Table that holds alarm status information on COOPWeb.  Updated by COOPIP On an ongoing basis"""
    using='coopweb'
    Alarmid=models.IntegerField(db_column='alarmid', unique=True)
    SubstationName=models.TextField(db_column='substationname', null=True, blank=True)
    AlarmStatus=models.TextField(db_column='alarmstatus', null=True, blank=True)
    CurrentEventid=models.IntegerField(db_column='currenteventid', null=True, blank=True)
    CurrentEventAcknowledgeIndicator=models.NullBooleanField(db_column='currenteventacknowledgeindicator', null=True, blank=True)
    CurrentEventNote=models.TextField(db_column='currenteventnote', null=True, blank=True)
    CurrentEventStartDateTime=models.DateTimeField(db_column='currenteventstartdatetime', null=True, blank=True)
    CurrentEventAcknowledgeDateTime=models.DateTimeField(db_column='currenteventacknowledgedatetime', null=True, blank=True)

    UpdateFromCOOPIPDateTime=models.DateTimeField(db_column='updatefromcoopipdatetime')
    class Meta:
        db_table=u'alarm'
        app_label='djangoproject'
    @staticmethod 
    def GetOrCreate(Alarmid):
        Alarms=Alarm.objects.filter(Alarmid=Alarmid)
        if(Alarms):
            return Alarms[0]
        else:
            New=Alarm()
            New.Alarmid = Alarmid
            New.UpdateFromCOOPIPDateTime=datetime.datetime.now()
            New.save()
            return New
    @staticmethod
    def PushDataToCOOPWeb():
        AlarmsUpdated = []
        NetworkDevices=djangoproject.models.NetworkDevice.objects.filter(NetworkDeviceModel__Name='DSC 1832 Alarm').filter(ActiveIndicator=True)
        for cOOPIPAlarm in NetworkDevices:
            alarm = Alarm.GetOrCreate(cOOPIPAlarm.id)
            alarm.SubstationName = cOOPIPAlarm.AMRSubstationName

            AlarmInfo = cOOPIPAlarm.GetRecentStatus()
            AlarmInfo=str(AlarmInfo[0]) + ' ' + str(AlarmInfo[1])

            CurrentEvent = djangoproject.models.AlarmEventHistory.objects.filter(NetworkDevice=cOOPIPAlarm).filter(CloseDateTime__isnull=True)
            if(CurrentEvent):
                ActiveEventString='*Active Event* '
                alarm.CurrentEventid = CurrentEvent[0].id
                alarm.CurrentEventAcknowledgeIndicator=bool(CurrentEvent[0].AcknowledgeDateTime)
                alarm.CurrentEventNote=CurrentEvent[0].Description
                alarm.CurrentEventStartDateTime=CurrentEvent[0].StartDateTime
                alarm.CurrentEventAcknowledgeDateTime=CurrentEvent[0].AcknowledgeDateTime
            else:
                ActiveEventString=''
                alarm.CurrentEventid = None
                alarm.CurrentEventAcknowledgeIndicator=None
                alarm.CurrentEventNote = ''
                alarm.CurrentEventStartDateTime=None
                alarm.CurrentEventAcknowledgeDateTime=None
            alarm.AlarmStatus = ActiveEventString + AlarmInfo
            alarm.UpdateFromCOOPIPDateTime=datetime.datetime.now()
            alarm.save()
            
            
       



